import { useState, useEffect } from "react";
import { useRequest } from 'ahooks'
import { useDispatch } from "react-redux";
// 
import useGetUserInfo from "./useGetUserInfo";
import { getUserInfoService } from '@/services/user'
import { loginReducer } from '@/store/userReducer'


function useLoadUserData() {
  // ajax请求用户数据后，直接放在 redux中
  // 这里不需要再返回数据了
  const [waitingUserData, setWaitingUserData] = useState(true);

  const dispatch=useDispatch()
  // ajax 
  const { run }=useRequest(getUserInfoService,{
    manual: true,
    onSuccess(res){
        const {username,nickname}=res
        dispatch(loginReducer({username,nickname}))
    },
    onFinally(){
        setWaitingUserData(false)
    }
  })

  const { username } =useGetUserInfo()
  useEffect(()=>{
    if(username){
        setWaitingUserData(false)
        return
    }
    run()
  },[username])

  return { waitingUserData };
}

export default useLoadUserData;
